package com.neusoft.service.impl;

import com.neusoft.dao.UserDao;
import com.neusoft.dao.UserRoleDao;
import com.neusoft.pojo.User;
import com.neusoft.pojo.UserRole;
import com.neusoft.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;

    @Resource
    UserRoleDao userRoleDao;

    /*查询用户列表的service实现方法*/
    @Override
    public List<User> userSelectAll(User user) {

        return userDao.userSelectAll(user);
    }

    /*添加用户的service实现方法*/
    @Transactional
    @Override
    public Integer insertUser(User user) {
        /*新增用户ID设置*/
        if (user.getId() == null || user.getId() == "") {
            user.setId(UUID.randomUUID().toString().replace("-", ""));
        }
        /*用户信息插入*/
        int i = userDao.insertUser(user);
        /*用户角色关系插入*/
        insertUserRole(user.getId(), user.getRoleId());
        return 1;
    }

    @Transactional
    @Override
    public Integer updateUser(User user) {
        String userId = Optional.ofNullable(user).map(User::getId).orElse("unKnown");
        String[] userRoleId = Optional.ofNullable(user).map(User::getRoleId).orElse(new String[]{"",null});
        /*首先删除原有角色用户关系*/
        deleteUserRole(userId);
        /*其次插入新的角色用户关系*/
        insertUserRole(userId, userRoleId);
        /*最后更新用户*/
        return userDao.updateUser(user);
    }

    @Override
    public Integer sequenceNext() {
        return userDao.sequenceNext();
    }

    @Override
    public Integer userDelete(String id) {
        return userDao.userDelete(id);
    }

    @Override
    public User userByUserId(String userId) {
        return userDao.userByUserId(userId);
    }


    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(String userId, String[] roleIds) {

        if (roleIds != null && (roleIds.length != 0)) {
            // 新增用户与角色关系
            List<UserRole> list = new ArrayList<>(roleIds.length);
            for (String roleId : roleIds) {
                UserRole ur = new UserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleDao.batchUserRole(list);
        }
    }

    /**
     * 删除用户角色信息
     *
     * @param userId  用户ID
     */
    public void deleteUserRole(String userId) {

        if (userId != null ) {
            userRoleDao.deleteUserRole(userId);
        }
    }

}
